<?php

namespace App\Models\WorkOrder;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class WorkOrderApplyManagerModel extends BaseModel
{
    use KfSoftDeletes;
    use KfUid;

    const STATUS_OFF = 1;  // 关闭
    const STATUS_ON  = 0;  // 正常


    protected $table = 'work_order_apply_manager';

    protected $fillable = [
        'workOrderNo',
        'role',
        'managerId',
        'managerName',
        'remark',
        'solution',
        'status',
        'isDeleted',
        'submitTime'
    ];

    /**
     * @return HasOne
     */
    public function applyMainRel(): HasOne
    {
        return $this->hasOne(WorkOrderApplyMainModel::class, "workOrderNo", "workOrderNo");
    }

    public static function add(
        string $workOrderNo,
        int $role,
        int $managerId,
        string $managerName = '',
        string $remark = "",
        int $submitTime = 0
    ) {
        if (!$managerName) {
            $managerName = WorkOrderUserRoleModel::query()->where('userId', $managerId)->value('name') ?? '';
        }

        return self::query()
                   ->create([
                       'workOrderNo' => $workOrderNo,
                       'role'        => $role,
                       'managerId'   => $managerId,
                       'managerName' => $managerName,
                       "remark"      => $remark,
                       "submitTime"  => $submitTime
                   ]);
    }

    /**
     * 获取订单的某个角色的所有负责人
     * @param string $workOrderNo
     * @param int $role
     * @return array
     */
    public static function getMangerIdsByRole(string $workOrderNo, int $role): array
    {
        return self::query()
                   ->where('workOrderNo', $workOrderNo)
                   ->where('role', $role)
                   ->pluck('managerId')
                   ->toArray();
    }


    /**
     * @param string $workOrderNo
     * @return Builder[]|Collection
     */
    public static function getManagersByWorkOrderNo(string $workOrderNo)
    {
        return self::query()->where("workOrderNo", $workOrderNo)->get();
    }

    /**
     * @return HasMany
     */
    public function remarkRel(): HasMany
    {
        return $this->hasMany(WorkOrderApplyManagerSubmitHistoryModel::class, "applyManagerId", "id")
                    ->where("type", WorkOrderApplyManagerSubmitHistoryModel::TYPE_REMARK);
    }

    /**
     * @return HasMany
     */
    public function solutionRel(): HasMany
    {
        return $this->hasMany(WorkOrderApplyManagerSubmitHistoryModel::class, "applyManagerId", "id")
                    ->where("type", WorkOrderApplyManagerSubmitHistoryModel::TYPE_SOLUTION);
    }
}
